import React from 'react';
import Title from 'Page/CommonComponents/Title';
import { createForm } from 'rc-form';
import { List, InputItem, Button, Picker } from 'antd-mobile';
import { CaptchaSeconds } from 'Constants/config';
import { checkMobilePhone } from 'Utils';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import './index.scss';

let canSendCaptcha = true;
class FormContent extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      remainingSecond: CaptchaSeconds,
      hasError: false
    };
    this.sendCaptcha = ::this.sendCaptcha;
    this.countDownSeconds = ::this.countDownSeconds;
  }
  componentWillReceiveProps(nextPorp) {
    this.setState({
      hasError: nextPorp.phoneError,
    });
  }
  componentWillUnmount() {
    canSendCaptcha = true;
    clearInterval(this.timer);
    this.timer = undefined;
  }
  // 发送验证码
  sendCaptcha() {
    const phone = this.props.form.getFieldsValue().phone;
    if (!canSendCaptcha) {
      return;
    }

    if (!phone) {
      return;
    }

    if (this.state.hasError) {
      return
    }

    canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);

    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone: phone.replace(/\s/g, ''),
        response: 'tmind'
      },
      error: (msg) => {
        this.setState({
          remainingSecond: 0,
        }, () => {
          canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      },
    });
    api.run();
  }
  /**
   * 验证码倒计时
   */
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  render() {
    const { getFieldProps } = this.props.form;
    const { remainingSecond, hasError } = this.state;
    return (
      <List>
        <InputItem
          {
            ...getFieldProps('name'
            )
          }
          placeholder="请输入姓名"
          labelNumber={6}
        >
          姓名
        </InputItem>
        <InputItem
          {
            ...getFieldProps('id_no'
            )
          }
          placeholder="请输入身份证号码"
          labelNumber={6}
        >
          身份证号码
        </InputItem>
        <InputItem
          {
            ...getFieldProps('phone'
            )
          }
          placeholder="请输入联系电话"
          labelNumber={6}
          type="phone"
          error={hasError}
        >
          联系电话
          <span className="get-code" onClick={this.sendCaptcha}>
            {remainingSecond === 60 || remainingSecond === 0
              ? '获取验证码'
              : <span>剩余{remainingSecond}s</span>
            }
          </span>
        </InputItem>
        <InputItem
          {
            ...getFieldProps('code'
            )
          }
          placeholder="请输入验证码"
          labelNumber={6}
        >
          验证码
        </InputItem>
      </List>
    );
  }
}
class ExamLogin extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      ExamType: [],
      selectType: [],
      formValue: [],
      illegalValue: [undefined],
      hasError: false
    };

    this.form = createForm({ onValuesChange: this.onFormValueChange.bind(this) })(FormContent);
    this.initTestType = ::this.initTestType;
  }
  componentWillMount() {
    this.initTestType();
  }
  onFormValueChange(props, value) {
    if (value.phone) {
      /* 验证手机号 */
      if (!checkMobilePhone(value.phone.replace(/\s/g, ''))) {
        this.setState({
          hasError: true
        });
      } else {
        this.setState({
          hasError: false
        });
      }
    }
    const valus = { ...this.loginForm.getFieldsValue(), ...value };
    const valueArr = Object.values(valus);
    const illegalValue = valueArr.filter(item => !item);

    this.setState({
      formValue: valus,
      illegalValue
    });
  }
  handleLogin() {
    const { formValue, selectType } = this.state;
    const data = { ...formValue, phone: formValue.phone.replace(/\s/g, '') };
    const api = new Api({
      method: 'POST',
      path: '/testers/user',
      data,
      success: ((json) => {
        canSendCaptcha = true;
        clearInterval(this.timer);
        this.timer = undefined;
        sessionStorage.setItem('questionNum', 1);
        this.props.dispatch(routerActions.push(`/exam/login/detail/${selectType[0]}/${json.id}`));
      }),
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  handleType(value) {
    this.setState({
      selectType: value,
    });
  }
  initTestType() {
    const api = new Api({
      method: 'GET',
      path: '/subjects',
      success: (res) => {
        const ExamType = res.length > 0 ? res.filter(item => item.state) : '';
        const newExamType = [];
        for (let i = 0, len = ExamType.length; i < len; i++) {
          const item = {
            value: ExamType[i].id,
            label: ExamType[i].type,
          };
          newExamType.push(item);
        }
        this.setState({
          ExamType: newExamType
        });
      },
      error: () => {}
    });
    api.run();
  }
  render() {
    const { ExamType, selectType, illegalValue, hasError } = this.state;
    return (
      <div className="exam-login-page">
        <Title title="知识测评" />
        <div className="exam-login">
          <this.form phoneError={hasError} ref={(ref) => { this.loginForm = ref; }} />
        </div>
        <div className="exam-type">
          <Picker
            data={ExamType}
            cols={1}
            onOk={this.handleType.bind(this)}
            value={selectType}
          >
            <List.Item arrow="horizontal">测试类别</List.Item>
          </Picker>
        </div>
        <div className="login-btn">
          <Button
            onClick={this.handleLogin.bind(this)}
            disabled={illegalValue.length > 0 || selectType.length === 0 || hasError}
          >我要测评</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(ExamLogin);

